<script setup lang="ts">
import useTable from '@/hooks/useTable'
import { get, post, Message, loadFile, message, download, checkBtnPermission, formatSortParams } from '@/utils'
import { ProductStatus, ProductType, ProductClient } from '@/enum/product'
import ProductModal from './components/ProductModal/index.vue'
import CommentList from './components/comment/List.vue'
import useModal from '@/hooks/useModal'
import useProduct from '@/hooks/useProduct'
import useOptions from '@/hooks/useOptions'
import { BtnPermission } from '@/enum/permission'
import BatchChangeClassify from './components/BatchChangeClassify.vue'
import ImportProductList from './components/ImportProductList.vue'
import BatchTransport from './components/BatchTransport.vue'
import BatchSaleNumModal from './components/BatchSaleNum.vue'
const selectedKeys = ref([])
const { store: batchClassifyStore } = useModal()
const { store: batchTransportStore } = useModal()
const { store: batchSaleNumStore } = useModal()
const { remove: del, changeStatus } = useProduct()
const { store } = useModal()
const { store: importStore } = useModal()
const { store: commentStore } = useModal()
const { formatColumns } = useTable()
const searchQuery = reactive({
  kind: 2,
  sellerGoodsCategoryId: '',
  categoryId: '',
})
const formRef = ref()
const actionRef = ref()
const pagination = {
  showPageSize: true,
  pageSize: 20,
}

/**平台商品分类 */
const { options: category } = useOptions({
  api: '/server-shop/sys-seller/seller/goods/category/tree',
})
/**获取分类的名字做展示 */
const getClassifyName = ids => {
  console.log('🚀 ~ ids:', ids)
  try {
    const classifyIds = (ids && JSON.parse(ids)) || []
    console.log('🚀 ~ classifyIds:', classifyIds)
    let nameList: string | string[] = []
    classifyIds.map(ids => {
      if (typeof ids == 'string') {
        const [item] = category.value.filter(f => f.id == ids)
        nameList.push(item.title)
      } else if (ids instanceof Array) {
        function findNodesByIds(tree, idSet, found: any[] = []) {
          for (const node of tree) {
            if (idSet.has(node.id)) {
              found.push(node)
            }
            if (node.children && node.children.length) {
              findNodesByIds(node.children, idSet, found)
            }
          }
          return found
        }
        const _list = findNodesByIds(category.value, new Set(ids))
        const res: string[] = []
        _list.map(item => {
          res.push(item.title)
        })
        nameList.push(res.join('/'))
      }
    })
    return nameList
  } catch (error) {
    console.log(error)
  }
}
/**平台商品分类 */
const { options: platformCategory } = useOptions({
  api: '/server-shop/sys-seller/goods/category/tree',
})
/**获取分类的名字做展示 */
const getClassifyName2 = ids => {
  try {
    const classifyIds = ids && JSON.parse(ids)
    let nameList: string | string[] = []
    classifyIds.map(ids => {
      if (typeof ids == 'string') {
        const [item] = platformCategory.value.filter(f => f.id == ids)
        nameList.push(item.title)
      } else if (ids instanceof Array) {
        function findNodesByIds(tree, idSet, found: any[] = []) {
          for (const node of tree) {
            if (idSet.has(node.id)) {
              found.push(node)
            }
            if (node.children && node.children.length) {
              findNodesByIds(node.children, idSet, found)
            }
          }
          return found
        }
        const _list = findNodesByIds(platformCategory.value, new Set(ids))
        const res: string[] = []
        _list.map(item => {
          res.push(item.title)
        })
        nameList.push(res.join('/'))
      }
    })
    return nameList
  } catch (error) {
    console.log(error)
  }
}
const request = (params: any, sort: any, filters: any): Promise<any> => {
  return new Promise((resolve, reject) => {
    const query = { size: params.pageSize, ...params, ...formatSortParams(sort), sellerGoodsCategoryId: searchQuery.sellerGoodsCategoryId[searchQuery.sellerGoodsCategoryId.length - 1] }
    // if (sort.sn) {
    //   query[sort.sn == 'ascend' ? 'ascs' : 'descs'] = 'sn'
    // }
    get(
      {
        url: '/server-shop/sys-seller/goods/page',
        data: query,
      },
      ({ data, code }) => {
        resolve({
          data: data.records,
          total: data.total,
          success: code == 200,
        })
      }
    )
  })
}

const columns = formatColumns([
  {
    title: '商品ID',
    dataIndex: 'id',
    width: 200,
    valueType: 'digit',
    ellipsis: true,
  },
  { title: '货架号', dataIndex: 'sn', width: 120, hideInSearch: false, sorter: true },

  {
    title: '商品图片',
    dataIndex: 'img',
    valueType: 'image',
    width: 90,
  },
  {
    title: '商品名称',
    dataIndex: 'name',
    width: 200,
    hideInSearch: false,
    ellipsis: true,
  },
  {
    title: '平台商品分类',
    dataIndex: 'categoryId',
    width: 200,
    // valueEnum: classifyValueEnum,
    formSlotName: 'categoryIdSearch',
    hideInSearch: false,
    ellipsis: true,
  },
  {
    title: '商户商品分类',
    dataIndex: 'sellerGoodsCategoryId',
    width: 200,
    // valueEnum: classifyValueEnum,
    formSlotName: 'sellerGoodsCategoryIdSearch',
    hideInSearch: false,
    ellipsis: true,
  },
  {
    title: '点击量',
    dataIndex: 'clickNum',
    width: 100,
    valueType: 'digit',
  },
  {
    title: '评价数',
    dataIndex: 'commentNum',
    width: 100,
    valueType: 'digit',
  },
  {
    title: '商品状态',
    dataIndex: 'status',
    width: 120,
    hideInSearch: false,
    valueType: 'select',
    valueEnum: {
      [ProductStatus.下架中]: { text: '下架中', status: 'Warning' },
      [ProductStatus.上架中]: { text: '上架中', status: 'Success' },
      [ProductStatus.审核不通过]: { text: '审核不通过', status: 'Error' },
      [ProductStatus.待审核]: { text: '待审核', status: 'Processing' },
      [ProductStatus.平台下架]: { text: '平台下架', status: 'Warning' },
    },
  },

  {
    title: '商品价',
    dataIndex: 'goodsPrice',
    width: 100,
    valueType: 'money',
    sorter: true,
  },
  {
    title: '成本价',
    dataIndex: 'costPrice',
    width: 100,
    sorter: true,
    render: ({ record }) => h('span', null, `￥${record.goodsSkuList[0].costPrice.toFixed(2)}`),
  },
  {
    title: '是否推荐',
    dataIndex: 'isPush',
    width: 90,
    valueEnum: {
      1: { text: '是' },
      0: { text: '否' },
    },
  },
  {
    title: '是否上架',
    dataIndex: 'isStatus',
    width: 90,
  },
  {
    title: '审核备注',
    dataIndex: 'remark',
    width: 150,
    ellipsis: true,
  },
  {
    title: '销量',
    dataIndex: 'salesVolume',
    width: 90,
  },
  {
    title: '排序',
    dataIndex: 'sort',
    width: 90,
    sorter: true,
  },
  {
    title: '虚拟销量',
    dataIndex: 'salesVolumeVirtual',
    width: 90,
    ellipsis: false,
  },
  { title: '库存', dataIndex: 'stock', width: 90 },
  { title: '创建时间', dataIndex: 'createTime', width: 200 },
  {
    title: '操作',
    dataIndex: 'option',
    width: 210,
    fixed: 'right',
    btnList: [
      {
        permission: BtnPermission.编辑,
        name: '编辑',
        handle: ({ record }) => store.handleShow(record, true),
      },
      {
        name: '删除',
        type: 'popconfirm',
        permission: BtnPermission.删除,
        tip: '确认删除该条数据吗',
        handle: ({ record }) => del(record.id, () => actionRef.value.reload()),
      },

      {
        name: '评论管理',
        permission: BtnPermission.查看,
        handle: ({ record }) => commentStore.handleShow(record),
      },
    ],
  },
])

/**修改商品状态 */
const changeProductStatus = item => {
  if (!checkBtnPermission(BtnPermission.编辑)) return false
  changeStatus({ ids: item.id }, item.status, () => actionRef.value.reload())
}
const batchChange = status => {
  if (!checkBtnPermission(BtnPermission.编辑)) return false
  if (!selectedKeys.value.length) {
    message({
      type: 'warning',
      content: '至少选择一条数据后操作！',
    })
    return
  }
  changeProductStatus({ id: selectedKeys.value.join(','), status })
}
const batchClassify = () => {
  if (!checkBtnPermission(BtnPermission.删除)) return false
  if (selectedKeys.value.length) {
    batchClassifyStore.handleShow({
      id: selectedKeys.value.join(','),
    })
  } else {
    message({
      type: 'warning',
      content: '至少选择一条数据后操作！',
    })
  }
}
const batchTransport = () => {
  if (!checkBtnPermission(BtnPermission.删除)) return false
  if (selectedKeys.value.length) {
    batchTransportStore.handleShow({
      id: selectedKeys.value.join(','),
    })
  } else {
    message({
      type: 'warning',
      content: '至少选择一条数据后操作！',
    })
  }
}
const batchDel = () => {
  if (!checkBtnPermission(BtnPermission.删除)) return false
  if (selectedKeys.value.length) {
    del(selectedKeys.value.join(','), () => actionRef.value.reload())
  } else {
    message({
      type: 'warning',
      content: '至少选择一条数据后操作！',
    })
  }
}
const batchSaleNum = () => {
  if (!checkBtnPermission(BtnPermission.删除)) return false
  if (selectedKeys.value.length) {
    batchSaleNumStore.handleShow({
      id: selectedKeys.value.join(','),
    })
  } else {
    message({
      type: 'warning',
      content: '至少选择一条数据后操作！',
    })
  }
}
</script>
<template>
  <div class="page">
    <ProTable
      :columns="columns"
      :request="request"
      column-resizable
      row-key="id"
      :form-ref="ref => (formRef = ref)"
      :pagination="pagination"
      header-title=" "
      :params="searchQuery"
      @reset="searchQuery.sellerGoodsCategoryId = ''"
      :scroll="{ x: 1000 }"
      :bordered="{ cell: true }"
      :action-ref="ref => (actionRef = ref)"
      v-model:selectedKeys="selectedKeys"
      :row-selection="{
        type: 'checkbox',
        showCheckedAll: true,
        onlyCurrent: false,
      }"
    >
      <template #option-render="{ dom, reset }">
        <component :is="dom[1]" />
        <component :is="dom[0]" />
        <!-- <a-button type="primary" @click="store.handleShow({})" v-permission="[BtnPermission.新建]">
          <template #icon>
            <icon-plus />
          </template>
          新建
        </a-button> -->
      </template>
      <template #tool-bar>
        <a-button type="primary" class="mb10" @click="importStore.handleShow({})" v-permission="['add']">
          <template #icon>
            <icon-pen-fill />
          </template>
          导入商品</a-button
        >
        <a-button class="mb10" type="primary" @click="batchClassify"> 批量修改分类</a-button>
        <a-button class="mb10" type="primary" @click="batchSaleNum"> 批量修改虚拟销量</a-button>
        <a-button class="mb10" type="primary" @click="batchTransport"> 批量修改运费模板</a-button>
        <a-popconfirm content="确认删除选中的数据吗?" @ok="batchDel">
          <a-button class="mb10" status="danger"> 批量删除</a-button>
        </a-popconfirm>
        <a-button class="mb10" status="success" @click="batchChange(ProductStatus.下架中)"> 批量上架</a-button>
        <a-button class="mb10" status="warning" @click="batchChange(ProductStatus.上架中)"> 批量下架</a-button>
      </template>
      <template #categoryIdSearch="{ record }">
        <a-cascader v-model="searchQuery.categoryId" :options="platformCategory" path-mode placeholder="请选择分类" :field-names="{ label: 'title', value: 'id' }" />
      </template>
      <template #sellerGoodsCategoryIdSearch="{ record }">
        <a-cascader v-model="searchQuery.sellerGoodsCategoryId" :options="category" path-mode placeholder="请选择分类" :field-names="{ label: 'title', value: 'id' }" />
      </template>
      <template #sellerGoodsCategoryId="{ record }">
        <a-space>
          <a-tag v-for="item in getClassifyName(record.sellerGoodsCategoryId)" color="blue">
            {{ item }}
          </a-tag>
        </a-space>
      </template>
      <template #categoryId="{ record }">
        <a-space>
          <a-tag v-for="item in getClassifyName2(record.categoryId)" color="blue">
            {{ item }}
          </a-tag>
        </a-space>
      </template>
      <template #isStatus="{ record }">
        <a-switch v-model="record.status" :disabled="![ProductStatus.上架中, ProductStatus.下架中].includes(record.status)" :checked-value="1" :unchecked-value="0" :before-change="val => changeProductStatus(record)">
          <template #checked> 是 </template>
          <template #unchecked> 否 </template>
        </a-switch>
      </template>
    </ProTable>
    <ProductModal v-if="store.show" v-model:show="store.show" :id="store.id" @confirm="actionRef.reload" :edit="store.edit" />
    <CommentList v-if="commentStore.show" v-model:show="commentStore.show" :id="commentStore.id" />
    <ImportProductList v-if="importStore.show" v-model:show="importStore.show" :id="importStore.id" @confirm="actionRef.reload" />
    <BatchChangeClassify v-if="batchClassifyStore.show" v-model:show="batchClassifyStore.show" :id="batchClassifyStore.id" @confirm="actionRef.reload" />
    <BatchTransport v-if="batchTransportStore.show" v-model:show="batchTransportStore.show" :id="batchTransportStore.id" @confirm="actionRef.reload" />
    <BatchSaleNumModal v-if="batchSaleNumStore.show" v-model:show="batchSaleNumStore.show" :id="batchSaleNumStore.id" @confirm="actionRef.reload" />
  </div>
</template>
